package vn.lumi.smarthome.ui;

import java.util.ArrayList;

import vn.lumi.smarthome.ActivityHelper;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Scene;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

public class AddSceneActivity extends AbstractSceneActivity {

	private static final int LOADER_ID = 0;

	@Override
	protected void onCreate(Bundle arg0) {
		// Doan nay can dat truoc super.onCreate();
		Intent intent = getIntent();
		mFloorID = intent.getIntExtra(EXTRA_FLOOR_ID, -1);
		mRoomID = intent.getIntExtra(EXTRA_ROOM_ID, -1);
		this.oldSceneName = "";
		super.onCreate(arg0);
		ActivityHelper.initialize(this);
	}

	@Override
	public void startLoadDeviceList(LoaderCallbacks<Device[]> loaderCallback) {
		Bundle bundle = new Bundle();
		bundle.putInt(AbstractSceneActivity.EXTRA_TYPE, TYPE_CREATE);
		getSupportLoaderManager().initLoader(LOADER_ID, bundle, loaderCallback)
				.forceLoad();
	}

	@Override
	public void saveScene() {
		// TODO Auto-generated method stub
		Device[] devices = this.mDeviceListAdapter.getDevices();
		// separate devices
		ArrayList<Device> normalDevices = new ArrayList<Device>();
		ArrayList<Device> RGBs = new ArrayList<Device>();
		for (int i = 0; i < devices.length; i++) {
			if (devices[i].isSelected()) {
				if (devices[i].getType_id() == Device.DEVICE_TYPE_RGB)
					RGBs.add(devices[i]);
				else
					normalDevices.add(devices[i]);
			}
		}

		int[] normalDevicesID = new int[normalDevices.size()];
		int[] normalDevicesState = new int[normalDevices.size()];
		for (int i = 0; i < normalDevices.size(); i++) {
			normalDevicesID[i] = normalDevices.get(i).getId();
			normalDevicesState[i] = normalDevices.get(i).getDeviceState()
					.getValue();
		}

		int[] RGBsID = new int[RGBs.size()];
		int[] RGBsState = new int[RGBs.size()];
		for (int i = 0; i < RGBs.size(); i++) {
			RGBsID[i] = RGBs.get(i).getId();
			RGBsState[i] = RGBs.get(i).getDeviceState().getRGB();
		}

		// put in content values
		ContentValues values = new ContentValues();
		this.newSceneName = this.medtName.getText().toString();
		values.put("hour", this.mCurrentHour);
		values.put("minute", this.mCurrentMinute);
		int currentSceneMode = 0;
		if (this.tgbSchedule.isChecked()) {
			currentSceneMode = Scene.SCENE_MODE_AUTO;
		} else {
			currentSceneMode = Scene.SCENE_MODE_NORMAL;
		}
		values.put("Scene mode", currentSceneMode);
		values.put("Scene Name", newSceneName);
		values.put("Room ID", mRoomID);
		values.put("Normal Devices ID",
				convertIntArrayToString(normalDevicesID));
		values.put("Normal Devices State",
				convertIntArrayToString(normalDevicesState));
		values.put("RGBs ID", convertIntArrayToString(RGBsID));
		values.put("RGBs State", convertIntArrayToString(RGBsState));

		// call back
		getApplicationContext().getContentResolver().update(
				TBL_Scene.CONTENT_URI_CREATE_SCENE, values, null, null);

		// show dialog

		this.dialog = new ProgressDialog(new ContextThemeWrapper(this, R.style.AlertDialogCustom) );
		this.dialog.setMessage(this.getString(R.string.txt_saving_scene_in_HC));
		this.dialog.setCancelable(false);
		this.dialog.show();
		// Thay doi font chu cua Dialog
		ChangeFont changeFont = new ChangeFont(getApplicationContext());
		TextView textView = (TextView) dialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView,
				R.string.txt_saving_scene_in_HC, LumiHome.font,
				LumiHome.sizeContent, Gravity.NO_GRAVITY, getResources()
						.getColor(R.color.greenActionbar));

		// set broadcast receiver
		AddSceneReceiver mAddSceneReceiver = new AddSceneReceiver(dialog);
		IntentFilter filter = new IntentFilter();
		filter.addAction(getApplicationContext().getString(
				R.string.vn_lumi_smarthome_create_scene_successful));
		filter.addAction(getApplicationContext().getString(
				R.string.vn_lumi_smarthome_create_scene_failed));
		filter.addAction(getApplicationContext().getString(
				R.string.vn_lumi_smarthome_create_scene_overload));
		this.registerReceiver(mAddSceneReceiver, filter);
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		Intent intentMainActivity = new Intent();
		intentMainActivity.putExtra("Scene", true);
		intentMainActivity.putExtra("RoomID", mRoomID);
		setResult(RESULT_OK, intentMainActivity);
		super.finish();
	}

	public class AddSceneReceiver extends BroadcastReceiver {

		private ProgressDialog mDialog;

		public AddSceneReceiver(ProgressDialog dialog) {
			mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			mDialog.cancel();
			unregisterReceiver(this);
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.vn_lumi_smarthome_create_scene_successful))) {
				finish();
			} else if (intent
					.getAction()
					.equals(context
							.getString(R.string.vn_lumi_smarthome_create_scene_failed))) {
				showCustomDialog(R.string.txt_error, R.string.txt_error_cannot_connect_HC);
			} else if (intent
					.getAction()
					.equals(context
							.getString(R.string.vn_lumi_smarthome_create_scene_overload))) {
				showCustomDialog(R.string.txt_error, R.string.txt_overloadScene);
			}
		}

	}
}
